package com.hl.qzzpbackend.aop;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.hl.qzzpbackend.annotation.AuthCheck;
import com.hl.qzzpbackend.constant.SessionConstant;
import com.hl.qzzpbackend.exception.BusinessException;
import com.hl.qzzpbackend.exception.ErrorCode;
import com.hl.qzzpbackend.exception.ThrowUtils;
import com.hl.qzzpbackend.model.enums.UserRoleEnum;
import lombok.SneakyThrows;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Title: AuthAdminInterceptor
 * @Author helong
 * @Package com.hl.qzzp.aop
 * @Date 2024/12/30 11:31
 * @description:
 */
@Aspect
@Component
public class AuthInterceptor {




    /**
     * 执行拦截
     * @param joinPoint 切入点
     * @param AuthCheck 权限校验注解
     * @return
     */
    @Around("@annotation(AuthCheck))")
    public Object doInterceptor(ProceedingJoinPoint joinPoint,  AuthCheck AuthCheck) throws Throwable {
        UserRoleEnum[] userRoleEnums = AuthCheck.mustRole();
        List<UserRoleEnum> passThrough = Arrays.stream(userRoleEnums).collect(Collectors.toList());

        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        // 获取当前登录用户
        Object obj = request.getSession().getAttribute(SessionConstant.USER_LOGIN_STATE);
        ThrowUtils.throwIf(obj == null, ErrorCode.NOT_LOGIN_ERROR);
        Map<String, Object> stringObjectMap = BeanUtil.beanToMap(obj);
        Integer role =(Integer) stringObjectMap.get("role");


        // 如果不需要权限，放行
        if(CollUtil.isEmpty(passThrough)){
            return joinPoint.proceed();
        }
        // 必须有权限，才会通过
        UserRoleEnum userRoleEnum = UserRoleEnum.getEnumByValue(role);
        if(userRoleEnum == null){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 可以通行的权限    有的权限
        boolean contains = passThrough.contains(userRoleEnum);
        if(!contains){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 放行
        return joinPoint.proceed();
    }
}
